<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <!--用户数据-->
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px" v-show="showSearch" >

          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="queryParams.realName" placeholder="请输入真实姓名" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="登录帐号" prop="loginName">
            <el-input v-model="queryParams.loginName" placeholder="请输入登录帐号" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="手机号码" prop="mobileNumber">
            <el-input v-model="queryParams.mobileNumber" placeholder="请输入手机号码" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="岗位名称" prop="postName">
            <el-input v-model="queryParams.postName" placeholder="请输入岗位名称" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="帐号状态" prop="statusCode">
            <el-select @change="handleQuery" v-model="queryParams.statusCode" size="small" clearable style="width: 150px" placeholder="请选择">
              <el-option key="" label="全部" value=""/>
              <el-option v-for="item in statusOptions" :key="item.dictCode" :label="item.dictName" :value="item.dictCode"/>
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>

          <el-form-item>
            <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary"  v-hasPermi="['saveSystemUser']"  icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" v-hasPermi="['updateSystemUser']"  icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" v-hasPermi="['deleteSystemUser']"  icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete">删除</el-button>
          </el-col>

          <right-toolbar :showSearch.sync="showSearch" @queryTable="querySystemUserPageResList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
                  @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column type="selection" align="center"/>
          <el-table-column label="头像" align="center" prop="headPortrait" width="100">
            <template slot-scope="scope">
              <img width="40" height="40" :src="scope.row.headPortrait" :onerror="$store.state.defaultAvatar"/>
            </template>

          </el-table-column>
          <el-table-column label="登录账号" align="left" prop="loginName"  width="100"/>
          <el-table-column label="真实姓名" align="left" prop="realName" width="100"/>
          <el-table-column label="用户性别" align="left" prop="genderName" width="100" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.genderColor">{{scope.row.genderName}}</span>
            </template>
          </el-table-column>

          <el-table-column label="手机号码" align="left" prop="mobileNumber" width="150"/>
          <el-table-column label="账号状态" sortable='custom' align="left" prop="statusName" sortBy="statusCode" width="150" >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.statusCode"
                active-value="NORMAL"
                inactive-value="FORBID"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="角色名称" align="left" prop="roleName"  width="200"/>
          <el-table-column label="所属岗位" align="left" prop="postName" width="200"/>
          <el-table-column label="所属部门" align="left" prop="createDeptName" width="200"/>
          <el-table-column label="创建时间" align="left" prop="createTime" sortable='custom'  width="200" />
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['updateSystemUser']" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" v-hasPermi="['deleteSystemUser']" icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>
              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['resetSystemUserPassword']">
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="resetSystemUserPassword" icon="el-icon-key"
                                    v-hasPermi="['resetSystemUserPassword']">重置密码</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
                    @pagination="querySystemUserPageResList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="80px">
        <el-form-item  v-if="form.userId === undefined" label="登录账号" prop="loginName">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.loginName" placeholder="请输入登录账号,注意确定保存后不可修改" minlength="1" maxlength="32" />
        </el-form-item>

        <el-form-item  v-if="form.userId !== undefined" label="登录账号" prop="loginName">
          <el-input disabled v-model="form.loginName"/>
        </el-form-item>

        <el-form-item label="登录密码" prop="password"  v-if="form.userId === undefined">
          <el-input v-model="form.password"  placeholder="请输入登录密码" type="password" minlength="1" maxlength="32" show-password/>
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.realName" placeholder="请输入真实姓名" minlength="1" maxlength="32" />
        </el-form-item>

        <el-form-item label="用户性别" prop="genderCode">
          <el-select :hide-required-asterisk="true" v-model="form.genderCode" clearable placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in genderOptions"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号码" prop="mobileNumber">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.mobileNumber" placeholder="请输入手机号码" minlength="11" maxlength="11" />
        </el-form-item>

        <el-form-item label="所属部门" prop="createDeptId">
          <treeselect v-model="form.createDeptId"
                      :options="deptOptions"
                      :defaultExpandLevel="3"
                      :normalizer="normalizerTree"
                      :show-count="false"
                      @input="changeCreateDeptId"
                      placeholder="请选择所属部门" />
        </el-form-item>

        <el-form-item label="所属岗位" prop="postId">
          <el-select v-model="form.postId" clearable placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in postOptions"
              :key="item.postId"
              :label="item.postName"
              :value="item.postId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="账号角色" prop="roleId">
          <el-select v-model="form.roleId" clearable placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            ></el-option>
          </el-select>
        </el-form-item>



        <el-form-item label="账号状态" prop="statusCode">
          <el-select :hide-required-asterisk="true" v-model="form.statusCode" clearable placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in statusOptions"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { queryNormalSelectSystemDeptTreeResList } from '@/api/system/systemDept'
import { queryNormalSelectSystemRoleResList } from '@/api/system/systemRole'
import { queryNormalSelectSystemPostResList } from '@/api/system/systemPost'
import {querySystemUserPageResList, saveSystemUser, updateSystemUser, deleteSystemUserByUserId, resetSystemUserPassword, updateSystemUserStatusByUserId} from '@/api/system/systemUser'
import { getDicListByDictCodeList } from '@/api/common/dict'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
//默认查询参数
let defaultQueryParams = {
  realName: undefined,
  loginName: undefined,
  startTime: undefined,
  endTime: undefined,
  mobileNumber: undefined,
  postName: undefined,
  statusCode:"",
  roleName: undefined,
  createDeptId: undefined,
  page: 1,
  rows: 10
}
export default {
  name: "systemUserAdmin",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 显示搜索条件
      showSearch: true,
      // table表格数据
      dataList: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示新增修改弹出层
      addUpdateOpen: false,
      // 部门树选项
      deptOptions: [],
      // 用户状态
      statusOptions: [],
      //性别选项
      genderOptions:[],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 增加修改表单参数
      form: {},
      // 查询参数
      queryParams: { ...defaultQueryParams },
      //列信息
      columns: [],
      // 新增修改表单校验
      addUpdateOpenRules: {
        loginName: [
          { required: true, message: "登录帐号不能为空",trigger: "blur" },
        ],
        password: [
          { required: true, message: "登录密码不能为空",trigger: "blur" },
        ],
        realName: [
          { required: true, message: "真实姓名不能为空",trigger: "blur" }
        ],
        genderCode: [
          { required: true, message: "用户性别必须选择"}
        ],
        mobileNumber: [
          { required: true, message: "手机号码不能为空",trigger: "blur" },
        ],
        createDeptId: [
          { required: true, message: "所属部门必须选择",trigger: "blur" }
        ],
        postId: [
          { required: true, message: "所属岗位必须选择"}
        ],
        roleId: [
          { required: true, message: "账号角色必须选择"}
        ],
        statusCode: [
          { required: true, message: "帐号状态必须选择"}
        ],
      }
    }
  },
  created() {
    this.querySystemUserPageResList();
    this.initDict();
  },

  methods: {
    //选择部门
    changeCreateDeptId(){
      this.$refs.form.validateField("createDeptId")
    },
    //创建初始
    createInit(){
      this.initDict();
      this.initPost();
      this.initRole();
      this.initDept();
    },
    //获取数据字典
    initDict(){
      let dictArr = ["STATUS","GENDER"];
      getDicListByDictCodeList(dictArr).then(res => {
        this.statusOptions = JSON.parse(JSON.stringify(res.data['STATUS']));
        this.genderOptions = JSON.parse(JSON.stringify(res.data['GENDER']));
      });
    },

    //获取可选岗位
    initPost(){
      queryNormalSelectSystemPostResList({}).then(response => {
        this.postOptions = response.data;
      });
    },
    //获取可选角色
    initRole(){
      queryNormalSelectSystemRoleResList({}).then(response => {
        this.roleOptions = response.data;
      });
    },
    //获取可选部门
    initDept(){
      queryNormalSelectSystemDeptTreeResList({}).then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 转换部门数据结构 */
    normalizerTree(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },

    /** 查询用户列表 */
    querySystemUserPageResList() {
      this.loading = true
      querySystemUserPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.dataList = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1;
      this.multiple = !selection.length
    },
    //排序
    tableSortChange(column){
      //格式化排序参数，构建中
      this.orderByFormat(this.queryParams,column);
      //执行查询方法
      this.querySystemUserPageResList()
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "resetSystemUserPassword":
          this.resetSystemUserPassword(row);
          break;
        default:
          break;
      }
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.statusCode === "FORBID" ? "禁用" : "启用";
      this.$modal.confirm('确认要"' + text + '""' + row.loginName + '"用户吗？').then(function() {
        return updateSystemUserStatusByUserId({"userId":row.userId});
      }).then(() => {
        this.$modal.msgSuccess("【"+row.loginName+"】用户"+text + "成功");
      }).catch(function() {
        row.statusCode = row.statusCode === "FORBID" ? "NORMAL" : "FORBID";
      });
    },
    /** 重置密码按钮操作 */
    resetSystemUserPassword(row) {
      this.$prompt('请输入"' + row.loginName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{1,16}$/,
        inputErrorMessage: "用户密码长度必须介于 1 和 16 之间"
      }).then(({ value }) => {
        resetSystemUserPassword({"userId":row.userId,"password": value}).then(response => {
          this.$modal.msgSuccess("密码重置成功，新密码是：" + value);
        });
      }).catch(() => {});
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.createInit();
      this.addUpdateOpen = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.createInit();
      row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
      //修改表单填充
      this.form = {...row};
      this.addUpdateOpen = true;
      this.title = "修改用户";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
      this.$confirm('确认删除"' + row.loginName + '"用户吗？', "警告", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning"
      }).then(function() {
        const userId={userId:row.userId}
        return deleteSystemUserByUserId(userId);
      }).then(response => {
        this.$modal.msgSuccess(response.message)
        this.querySystemUserPageResList();
      }).catch(function() {});
    },

    /** 提交保存或修改按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId !== undefined) {
            updateSystemUser(this.form).then(response => {
              this.$modal.msgSuccess(response.message)
              this.querySystemUserPageResList();
              this.addUpdateOpen = false
            });
          } else {
            saveSystemUser(this.form).then(response => {
              this.$modal.msgSuccess(response.message)
              this.querySystemUserPageResList();
              this.addUpdateOpen = false
            });
          }
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.querySystemUserPageResList()
    },
    /** 重置按钮操作 */
    resetQuery(fromId) {
      this.dateRange = [];
      this.resetForm(fromId);
      this.handleQuery()
    },
    // 取消修改增加弹出层按钮
    cancelAddUpdateOpen() {
      this.addUpdateOpen = false
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        genderCode: undefined,
        postId: undefined,
        roleId: undefined,
        statusCode: undefined,
        realName: undefined,
        mobileNumber: undefined,
        createDeptId: undefined,
        deptOptions: [],
        roleOptions: [],
        postOptions: [],
        statusOptions: []
      };
      this.resetForm('form')
    }
  }
}
</script>
